package com.arpa.wms.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.IterUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.arpa.core.web.MediaTypes;
import com.arpa.core.web.Result;
import com.arpa.ntocc.common.common.Page;
import com.arpa.ntocc.common.common.constant.StrConsts;
import com.arpa.ntocc.common.common.exception.ServiceException;
import com.arpa.ntocc.common.common.util.ShipmentWarehouseValidate;
import com.arpa.ntocc.common.common.util.UserUtil;
import com.arpa.ntocc.common.common.util.excel.EasyExcelUtil;
import com.arpa.ntocc.common.security.annotation.NeedLogin;
import com.arpa.wms.domain.consts.CommonConst;
import com.arpa.wms.domain.consts.PropertyConst;
import com.arpa.wms.domain.dto.GoodsUnitDTO;
import com.arpa.wms.domain.dto.GoodsUnitExcelDTO;
import com.arpa.wms.domain.entity.GoodsUnit;
import com.arpa.wms.domain.enums.StatusEnum;
import com.arpa.wms.domain.vo.GoodsUnitExcelVO;
import com.arpa.wms.domain.vo.UnitVO;
import com.arpa.wms.service.IGoodsUnitService;
import io.swagger.annotations.*;
import lombok.extern.log4j.Log4j2;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * @author: Allen chen
 * @Date 2020/8/11
 * @Description:
 */
@Api(tags = "单位")
@RestController
@RequestMapping(value = "/goodsUnit", produces = "application/json;charset=UTF-8")
@Log4j2
public class GoodsUnitController {

    private final IGoodsUnitService iGoodsUnitService;

    public GoodsUnitController(IGoodsUnitService iGoodsUnitService) {
        this.iGoodsUnitService = iGoodsUnitService;
    }

    @ApiOperation(value = "商品单位列表", notes = "单位单位列表接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @ApiResponses(@ApiResponse(code = 0, message = "success", response = UnitVO.class))
    @NeedLogin
    @GetMapping
    public Result list(GoodsUnitDTO unitDTO, HttpServletRequest request) {
        try {

            //校验授权仓库code和货主code不能为空
            Map<String, List<String>> authMap = ShipmentWarehouseValidate.validateShipmentCodesAndWarehouseCodes();
            //获取所属机构过滤
            unitDTO.setGroupCode(UserUtil.getBranchCode());
            unitDTO.setShipmentCodes(authMap.get(CommonConst.SHIPMENT_CODES));
            UnitVO unitSum = iGoodsUnitService.queryListSum(unitDTO);
            List<UnitVO> unitVOList = iGoodsUnitService.queryList(unitDTO);

            Page returnPage = new Page(unitDTO.getPageNum(), unitDTO.getPageSize());
            returnPage.setRecords(unitVOList);
            returnPage.setTotal(unitSum.getTotal());
            returnPage.setSumObject(unitSum);
            return Result.ok().data(returnPage);
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }

    @ApiOperation(value = "模糊查询货主商品单位", notes = "模糊查询货主商品单位")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000"),
            @ApiImplicitParam(name = "keywords", value = "商品单位名称", paramType = "path", dataType = "String"),
            @ApiImplicitParam(name = "shipmentCode", value = "货主code", paramType = "path", dataType = "String")
    })
    @NeedLogin
    @GetMapping(value = "/search")
    public Result search(@RequestParam(value = "keywords",defaultValue = "") String keywords,@RequestParam(value = "shipmentCode",required = true) String shipmentCode, HttpServletRequest request) {
        try {
            List<Map<String, Object>> result = iGoodsUnitService.search(keywords,shipmentCode);
            return Result.ok().data(result);
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }

    @ApiOperation(value = "添加 单位 ", notes = "添加 单位 ")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer 123456")
    })
    @NeedLogin
    @PostMapping(value = "/save")
    public Result save(GoodsUnit unit, HttpServletRequest request) {
        try {
            unit.setGroupCode(UserUtil.getBranchCode());
            iGoodsUnitService.save(unit);
            return Result.ok("添加成功");
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }

    @ApiOperation(value = "获取单位详情", notes = "获取单位详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer 123456"),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000"),
            @ApiImplicitParam(name = "code", value = "单位code", paramType = "path", dataType = "String")
    })
    @ApiResponses(@ApiResponse(code = 0, message = "success", response = GoodsUnit.class))
    @NeedLogin
    @GetMapping(value = "/{code}")
    public Result detail(@PathVariable String code, HttpServletRequest request) {
        try {
            GoodsUnit one = iGoodsUnitService.getOneByCode(code);
            one.setGroupCode(UserUtil.getBranchCode());
            return Result.ok().data(one);
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }

    @ApiOperation(value = "修改单位", notes = "修改单位")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @NeedLogin
    @PutMapping("/update")
    public Result update(GoodsUnit unit, HttpServletRequest request) {

        if (StrUtil.isBlank(unit.getCode())) {
            return Result.error("code不能为空");
        }
        int updateNum = iGoodsUnitService.updateByCode(unit);
        if (updateNum == 0) {
            return Result.error("没有更新数据！code:" + unit.getCode());
        } else {
            return Result.ok("修改成功");
        }
    }

    @ApiOperation(value = "删除单位信息", notes = "删除单位信息", produces = MediaTypes.JSON_UTF_8)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000"),
            @ApiImplicitParam(name = "codes", value = "单位code", paramType = "path", dataType = "String")
    })
    @NeedLogin
    @DeleteMapping(value = "/{code}")
    public Result delete(@RequestParam List<String> codes, HttpServletRequest request) {
        try {
            Map<String, Object> result = iGoodsUnitService.removeByCode(codes);
            Integer success = MapUtil.getInt(result, PropertyConst.SUCCESS);
            List<String> notDelete = MapUtil.get(result, "notDelete", List.class);
            int failNum = codes.size() - success;
            StringBuilder builder = new StringBuilder();
            builder.append("删除成功" + success + "条；失败" + failNum + "条；");
            if(IterUtil.isNotEmpty(notDelete)){
                for (String m:notDelete) {
                    builder.append("<br><font color='red'>商品单位【"+m+"】删除失败，已被启用过;</font>");
                }
            }
            return Result.ok(builder.toString());
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }

    @ApiOperation(value = "启用单位", notes = "启用单位")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @NeedLogin
    @PutMapping("/active")
    public Result active(@RequestParam List<String> codes, HttpServletRequest request) {
        Map<String, Object> result = iGoodsUnitService.batchUpdateStatus(codes, StatusEnum.ACTIVE.getValue());
        Integer success = MapUtil.getInt(result, PropertyConst.SUCCESS);
        int failNum = codes.size() - success;
        return Result.ok("启用成功" + success + "条；失败" + failNum + "条；");
    }

    @ApiOperation(value = "停用单位", notes = "停用单位")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @NeedLogin
    @PutMapping("/unactive")
    public Result unactive(@RequestParam List<String> codes, HttpServletRequest request) {

        Map<String, Object> result = iGoodsUnitService.batchUpdateStatus(codes, StatusEnum.UNACTIVE.getValue());
        List<String> msg = MapUtil.get(result,"msg",List.class);
        String message = "";
        if(IterUtil.isNotEmpty(msg)){
            for(String m: msg){
                message+="<br><font color='red'>商品单位【"+m+"】停用失败，商品正在使用中;</font>";
            }
        }
        return Result.ok("停用成功" + (MapUtil.getInt(result,PropertyConst.SUCCESS) == null ? 0 : MapUtil.getInt(result,PropertyConst.SUCCESS))  + "条；失败" + (MapUtil.getInt(result,"fail") == null ? 0 : MapUtil.getInt(result,"fail")) + "条；"+message);


    }


    @ApiOperation(value = "获取货主单位列表", notes = "获取货主单位列表接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @NeedLogin
    @GetMapping(value = "/findUnitByShipmentCode")
    public Result findUnitByShipmentCode(String shipmentCode, HttpServletRequest request) {
        try {
            List<Map<String, Object>> unitVOList = iGoodsUnitService.findUnitByShipmentCode(shipmentCode);
            return Result.ok().data(unitVOList);
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }

    @ApiOperation(value = "商品单位 导入 预览", notes = "商品单位 导入 预览")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000"),
            @ApiImplicitParam(name = "filePath", value = "文件路径", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "isView", value = "是否已经预览", required = true, paramType = "query", dataType = "Integer")
    })
    @PostMapping("/goodsUnitExcelView")
    public Result initializationView(String filePath, Integer isView, HttpServletRequest request) {
        try {

            java.net.URL url = new java.net.URL(filePath);
            List<GoodsUnitExcelDTO> list = EasyExcelUtil.read(url.openStream(), GoodsUnitExcelDTO.class,2);
            if(CollUtil.isEmpty(list)) {
                throw new ServiceException("文件内容为空");
            }
            List<GoodsUnitExcelVO> goodsUnitExcelDtoS = iGoodsUnitService.goodsUnitExcelView(list);
            return new Result().data(goodsUnitExcelDtoS);
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 预览后导入库位
     * @param importCode 预览时生成的导入码
     * @param request
     * @return
     */
    @ApiOperation(value = "商品单位 导入", notes = "商品单位 导入")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000"),
            @ApiImplicitParam(name = "filePath", value = "文件路径", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "isView", value = "是否已经预览", required = true, paramType = "query", dataType = "Integer")
    })
    @PostMapping("/importGoodsUnit")
    public Result importGoodsUnit(@RequestParam("importCode") String importCode, HttpServletRequest request) {
        try {
            Result result = iGoodsUnitService.importUnits(importCode);
            return result;
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }
}
